from flask import current_app,request
from celery.utils.log import get_task_logger
import logging.config
from celery.task import Task
from app import celery
import pymysql
from pymysql.cursors import DictCursor
from datetime import datetime,timedelta
from xml.dom.minidom import Document
import os
import time
import requests
from app.config import Config
logger = get_task_logger('myapp')

LOG_CONFIG = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'simple': {
            'datefmt': '%Y-%m-%d %H:%M:%S',
            'format': '%(asctime)s \"%(pathname)s：%(module)s:%(funcName)s:%(lineno)d\" [%(levelname)s]- %(message)s'
        }
    },
    'handlers': {
        'celery': {
            'level': 'DEBUG',
            'formatter': 'simple',
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': 'log/celery_logger.log',
            'when': 'midnight',
            'encoding': 'utf-8',
        },
    },
    'loggers': {
         'myapp': {
            'handlers': ['celery'],
            'level': 'INFO',
            'propagate': True,
         }
    }
}

logging.config.dictConfig(LOG_CONFIG)

class MyTask(Task):
    def on_success(self, retval, task_id, args, kwargs):
        logger.info('task done: {0}'.format(retval))
        return super(MyTask, self).on_success(retval, task_id, args, kwargs)

    def on_failure(self, exc, task_id, args, kwargs, einfo):
        logger.error('task fail, reason: {0}'.format(exc))
        return super(MyTask, self).on_failure(exc, task_id, args, kwargs, einfo)

# 重启uwsgi服务
@celery.task(base=MyTask)
def restart_uwsgi_sever():
    try:
        res=os.system('sudo /vdc/anaconda3/bin/uwsgi --reload /vdb/python/zimu_blog/uwsgi/uwsgi1.pid&&sudo /vdc/anaconda3/bin/uwsgi --reload /vdb/python/zimu_blog/uwsgi/uwsgi2.pid&&sudo /vdc/anaconda3/bin/uwsgi --reload /vdb/python/zimu_blog/uwsgi/uwsgi3.pid >out.txt 2>&1')
        if res == 0:
            logger.info('restart uwsgi sever success')
        else:
            with open("out.txt","r") as file:
                logger.error(file.read())
        return res
    except Exception as e:
        logger.error('restart uwsgi sever fail,%s', (str(e)))
        return 'restart uwsgi sever fail'

#更新新闻链接到网站地图
@celery.task(base=MyTask)
def update_sitemap_by_news():
    try:
        now_data = datetime.now().date()
        yesterday_data = now_data - timedelta(days=1)
        conn1 = pymysql.Connect(host=Config.MYSQL_HOST, port=Config.MYSQL_PORT, user=Config.MYSQL_USER, password=Config.MYSQL_PW, database='yuwuzheng',
                                charset='utf8')
        cursor1 = conn1.cursor(DictCursor)
        cursor1.execute('select id from ywz_news where pubtime_date between %s and %s', (yesterday_data, now_data))

        conn2 = pymysql.Connect(host=Config.MYSQL_HOST, port=Config.MYSQL_PORT, user=Config.MYSQL_USER, password=Config.MYSQL_PW,
                                database=Config.MYSQL_NAME, charset='utf8mb4')
        cursor2 = conn2.cursor()
        for item in cursor1.fetchall():
            cursor2.execute('insert into zimu_sitemap values(Null,%s,%s,%s,%s)',
                            ('https://zimu.website/news/' + str(item['id']), '0.5', now_data, 'never'))
        conn2.commit()
        cursor2.close()
        cursor1.close()
        conn2.close()
        conn1.close()
        return 'update_sitemap_by_news success'
    except Exception as e:
        logger.error('update_sitemap_by_news fail,%s'.format(str(e)))
        return 'update_sitemap_by_news fail'


# 更新网站地图xml文件
@celery.task(base=MyTask)
def update_sitemap_xml():
    try:
        doc = Document()
        root = doc.createElement('urlset')
        root.setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9')
        root.setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance')
        root.setAttribute('xsi:schemaLocation', 'http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd')
        doc.appendChild(root)
        conn = pymysql.Connect(host=Config.MYSQL_HOST, port=Config.MYSQL_PORT, user=Config.MYSQL_USER, password=Config.MYSQL_PW,
                                database=Config.MYSQL_NAME, charset='utf8mb4')
        cursor = conn.cursor(DictCursor)
        cursor.execute('select * from zimu_sitemap')
        for item in cursor.fetchall():
            url = doc.createElement('url')
            loc = doc.createElement('loc')
            loc.appendChild(doc.createTextNode(item['loc']))
            priority = doc.createElement('priority')
            priority.appendChild(doc.createTextNode(item['priority']))
            lastmod = doc.createElement('lastmod')
            lastmod.appendChild(doc.createTextNode(str(item['lastmod'])))
            changefreq = doc.createElement('changefreq')
            changefreq.appendChild(doc.createTextNode(item['changefreq']))
            url.appendChild(loc)
            url.appendChild(priority)
            url.appendChild(lastmod)
            url.appendChild(changefreq)
            root.appendChild(url)
        with open(os.path.join(os.path.abspath(os.path.dirname(os.path.dirname(__file__))), request.path[1:]),'w',encoding='utf-8') as fp:
            doc.writexml(fp, indent='', addindent='\t', newl='\n', encoding='utf-8')
        return 'update_sitemap_xml success'
    except Exception as e:
        logger.error('update_sitemap_xml fail,%s'.format(str(e)))
        return 'update_sitemap_xml fail'

# 更新推广
@celery.task(base=MyTask)
def update_promotion():
    try:
        res = requests.get(
            'https://query.aliyun.com/rest/merak.api/deliveryInfo?id=8764170&count=30&env=com&realTimeRecommend=[]&byGroup=1&lang=zh',
            headers={
                'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36 Edg/98.0.1108.43'})
        json_content = res.json()
        if json_content['code'] == 200:
            conn = pymysql.Connect(host=Config.MYSQL_HOST, port=Config.MYSQL_PORT, user=Config.MYSQL_USER,
                                   password=Config.MYSQL_PW,
                                   database=Config.MYSQL_NAME, charset='utf8mb4')
            cursor = conn.cursor(DictCursor)
            promotion_list = json_content['data']['infoList'][1]['children']
            for promotion_item in promotion_list:
                if 'link' in promotion_item['exts']:
                    link = promotion_item['exts']['link']['value']
                else:
                    link = promotion_item['link']
                link += '?userCode=zc2vjyju'
                cursor.execute('select count(*) from zimu_promotion where href=%s', (link,))
                if cursor.fetchone():
                    continue
                cursor.execute('insert into zimu_promotion values(Null,%s,%s,%s,%s,%s,%s,%s)',
                               (promotion_item['name'], promotion_item['title'],
                                promotion_item['exts']['friendequity']['value'],
                                promotion_item['exts']['description']['value'],
                                link,
                                time.strftime('%Y-%m-%d', time.localtime(promotion_item['startTime'] / 1000.0)),
                                time.strftime('%Y-%m-%d', time.localtime(promotion_item['endTime'] / 1000.0))))
            conn.commit()
            cursor.close()
            conn.close()
        else:
            return 'update_promotion ok'
        return 'update_promotion success'
    except Exception as e:
        logger.error('update_promotion fail,%s'.format(str(e)))
        return 'update_promotion fail'
